<script setup lang="ts">
import VChart from 'vue-echarts'
import { useChartToolboxDataView } from '@/mixins/MixinChartToolboxDataView'
import { useChartAutoResize } from '@/mixins/MixinChartAutoResize'
import { useChartTooltipTheme } from '@/mixins/MixinChartTooltipTheme'
import type { VChartInstance } from '@/types'

const props = withDefaults(
  defineProps<{
    title: string
    data: { name: string, data: number[], unit: string }[]
    x: string[]
  }>(),
  {
    title: '折线图',
    data: () => [],
    x: () => [],
  },
)

const { dataView: chartToolboxDataView } = useChartToolboxDataView(() => ({
  dataViewFirstCellName: '时间',
}))
const tooltipTheme = useChartTooltipTheme()
const chartOption = computed(() => {
  return {
    title: {
      show: false,
      text: props.title,
      textStyle: {
        fontFamily: 'PingFang SC',
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
      } as any,
    },
    tooltip: {
      trigger: 'axis',
      ...tooltipTheme,
    },
    legend: {
      orient: 'horizontal',
      left: 'center',
      bottom: 16,
      data: props.data.map(v => `${v.name}${v.unit ? `(${v.unit})` : ''}`),
    },
    grid: {
      top: '18%',
      left: '2%',
      right: '4.5%',
      bottom: 60,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.x,
    },
    yAxis: {
      type: 'value',
    },
    toolbox: {
      show: true,
      left: 'right',
      top: 0,
      feature: {
        dataView: unref(chartToolboxDataView),
        magicType: {
          type: ['line', 'bar'],
        },
      },
    },
    series: [
      ...props.data.map(v => ({
        name: `${v.name}${v.unit ? `(${v.unit})` : ''}`,
        type: 'line',
        data: v.data,
      })),
    ],
  }
})

const chartRef = ref<VChartInstance>()
useChartAutoResize(chartRef, () => ({
  autoresize: true,
}))

const { theme } = storeToRefs(useDesignStore())
watchEffect(() => {
  if (chartRef.value) {
    chartRef.value.setOption({
      theme: theme.value,
    })
  }
})
</script>

<template>
  <VChart
    ref="chartRef" :option="chartOption" style="width:100%;height:100%;"
    :init-options="{
      locale: 'zh',
    }"
    :theme="theme"
  />
</template>
